package com.github.postsanf.yinian.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.postsanf.yinian.FrageActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.LocalManageVideoSelAdapter;
import com.github.postsanf.yinian.bean.YNVideoInfo;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.fragment.VideoAlbumFragment;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.UIHelper;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

public class VideoLocalSelectActivity extends FrageActivity implements View.OnClickListener {
    private GridView mGirdViewtop;
    private LocalManageVideoSelAdapter topAdapter;
    private ProgressDialog mProgressDialog;
    public static List<YNVideoInfo> mVideos = new ArrayList<>();
    private RelativeLayout layout_down;
    private LinearLayout down;
    private ImageView down_title_cover;
    private ImageView title_cover;
    private VideoAlbumFragment cameraAlbumFragment;
    public static boolean mainImage = false;
    private long fristtime = 0;
    public static boolean IsSmall = false;
    private TextView tv_next;
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0x110:
                    if (mProgressDialog != null)
                        mProgressDialog.dismiss();
                    if (mVideos.size() > 0) {
                        sendBroadcast(new Intent("updatebuttomgridview"));
                    } else {
                        Toast.makeText(VideoLocalSelectActivity.this, "未检测到视频！", Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    };

//    public static boolean fromfrist = false;
//    public static int fromfristgid = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_localvideo_select);
        registerBoradcastReceiver();
        mVideos.clear();
        SelectedImg.mSelectedImage.clear();
        SelectedImg.mSelectedVideo.clear();
        mProgressDialog = new ProgressDialog(this, ProgressDialog.THEME_HOLO_LIGHT);
        mProgressDialog.setTitle("");
        mProgressDialog.setMessage(CommonConstants.TIP_LOAD_DATA);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setCancelable(true);
        initView();
        getVideos();
    }

    private void initView() {
        tv_next = (TextView) findViewById(R.id.tv_next);
//        if (getIntent() != null) {
//            mainImage = getIntent().getBooleanExtra("mainImage", false);
//            fromfrist = getIntent().getBooleanExtra("fromfrist", false);
//            fromfristgid = getIntent().getIntExtra("gid", 0);
//        }
//        if (!mainImage) {
//            tv_next.setVisibility(View.GONE);
//        } else {
//            tv_next.setVisibility(View.VISIBLE);
//        }
        findViewById(R.id.iv_back).setOnClickListener(this);
        tv_next.setOnClickListener(this);
        cameraAlbumFragment = new VideoAlbumFragment();
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_contaier, cameraAlbumFragment)
                .commit();
        mGirdViewtop = (GridView) findViewById(R.id.gv_image_top);
        topAdapter = new LocalManageVideoSelAdapter(VideoLocalSelectActivity.this, R.layout.yn_video_grid_item_sel);
        mGirdViewtop.setAdapter(topAdapter);
        layout_down = (RelativeLayout) findViewById(R.id.layout_down);
        down = (LinearLayout) findViewById(R.id.down);
        title_cover = (ImageView) findViewById(R.id.title_cover);
        down_title_cover = (ImageView) findViewById(R.id.down_title_cover);
        layout_down.setOnClickListener(this);
        title_cover.setOnClickListener(this);
        down_title_cover.setOnClickListener(this);
        findViewById(R.id.ll_album_title_btn).setOnClickListener(this);
    }

    private void getVideos() {
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            showToast("暂无外部存储");
            return;
        }
        mProgressDialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Cursor cursor = getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null,
                        MediaStore.Video.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"video/mp4", "video/3gp"},
                        MediaStore.Video.Media.DATE_MODIFIED);
                if (cursor == null) {
                    return;
                }
                while (cursor.moveToNext()) {
//                    int id = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
//                    String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));  //视频文件的标题内容
//                    String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.ALBUM));
//                    String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.ARTIST));
//                    String displayName = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME));
//                    String mimeType = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE));
                    String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
                    long duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));
//                    long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
//                    Log.i("xjs", "duration===>" + duration);
                    if (duration > 0 && duration < 10 * 60 * 1000) {
                        Bitmap dbitmap = UIHelper.getVideoThumbnail(path);
                        if (dbitmap != null)
                            mVideos.add(new YNVideoInfo(0, "", "", "", "", "", path, 0, duration, dbitmap));
                    }
                }
                cursor.close();
                mHandler.sendEmptyMessage(0x110);
            }
        }).start();
    }

    boolean bb = false;

    public void ToSetDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);
        final AlertDialog dlg = builder.create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.pub_dialog);
        window.setBackgroundDrawableResource(R.color.transparent);
        WindowManager.LayoutParams layout = dlg.getWindow().getAttributes();
        layout.width = DisplayUtils.getScreenWidthPixels(this) - DisplayUtils.dp2px(this, 35 * 2);
        dlg.getWindow().setAttributes(layout);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText("提示");
        TextView content = (TextView) window.findViewById(R.id.pp_content);
        content.setText("是否放弃编辑?");
        TextView cancel = (TextView) window
                .findViewById(R.id.btn_cancel);
        cancel.setText("继续编辑");
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
            }
        });
        final TextView ok = (TextView) window.findViewById(R.id.btn_ok);
        ok.setText("确定");
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
                finish();
            }
        });
    }

    @Override
    public void onBackPressed() {
//        if (!mainImage) {
//            sendBroadcast(new Intent("updateImageNum"));
//            finish();
//        } else {
        if (new Long(System.currentTimeMillis() - fristtime) > 4900) {
            ToSetDialog();
        } else {
            finish();
        }
//        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
//                if (!mainImage) {
//                    sendBroadcast(new Intent("updateImageNum"));
//                    finish();
//                } else {
                if (new Long(System.currentTimeMillis() - fristtime) > 4900) {
                    ToSetDialog();
                } else {
                    finish();
                }
//                }
                break;
            case R.id.tv_next:
                if (SelectedImg.mSelectedImage.size() == 0) {
                    Toast.makeText(this, "选择一个视频", Toast.LENGTH_SHORT).show();
                    return;
                }
                intent2Activity(VideoLocalEditActivity.class);
                break;
            case R.id.layout_down:
                if (!bb) {
                    bb = true;
                    Animation translateAnimation = new TranslateAnimation(0, 0, 0, -UIHelper.dip2px(VideoLocalSelectActivity.this, 260));
                    translateAnimation.setDuration(400);
                    down.startAnimation(translateAnimation);
                    translateAnimation.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {
                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            sendBroadcast(new Intent("topgridviewclose"));
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {
                        }
                    });
                    AlphaAnimation alphaAnimationcover = new AlphaAnimation(0.0f, 1.0f);
                    alphaAnimationcover.setDuration(400);
                    title_cover.startAnimation(alphaAnimationcover);
                    title_cover.setVisibility(View.VISIBLE);
                    down_title_cover.setVisibility(View.VISIBLE);
                } else {
                    bb = false;
                    Animation translateAnimation = new TranslateAnimation(0, 0, 0, UIHelper.dip2px(VideoLocalSelectActivity.this, 260));
                    translateAnimation.setDuration(400);
                    down.startAnimation(translateAnimation);
                    translateAnimation.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {
                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            sendBroadcast(new Intent("topgridviewopen"));
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {
                        }
                    });
                }
                break;
            case R.id.title_cover:
            case R.id.down_title_cover:
                bb = false;
                AlphaAnimation alphaAnimationcover = new AlphaAnimation(1.0f, 0.0f);
                alphaAnimationcover.setDuration(400);
                title_cover.startAnimation(alphaAnimationcover);
                down_title_cover.startAnimation(alphaAnimationcover);
                alphaAnimationcover.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        title_cover.setVisibility(View.GONE);
                        down_title_cover.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }
                });
                Animation translateAnimation = new TranslateAnimation(0, 0, 0, UIHelper.dip2px(VideoLocalSelectActivity.this, 260));
                translateAnimation.setDuration(400);
                down.startAnimation(translateAnimation);
                translateAnimation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        sendBroadcast(new Intent("topgridviewopen"));
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }
                });
                break;
        }
    }


    // 清除选中并退出
    private void clearAll() {
        SelectedImg.mSelectedImage.clear();
        SelectedImg.mSelectedVideo.clear();
        finish();
    }

    // 广播接收
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionCloseAlbum:
                    int noClear = intent.getExtras().getInt(ACTIONs.aIsClearSelect);
                    if (1 == noClear) {
                        finish();
                    } else {
                        clearAll();
                    }
                    break;
                case ACTIONs.actionUpdateUpNum:
                    break;
                case "updatetopgridview":
                    topAdapter.notifyDataSetChanged();
                    break;
                case "topgridviewclose":
                    mGirdViewtop.setVisibility(View.GONE);
                    break;
                case "topgridviewopen":
                    AlphaAnimation alphaAnimationtop = new AlphaAnimation(0.0f, 1.0f);
                    alphaAnimationtop.setDuration(700);
                    mGirdViewtop.startAnimation(alphaAnimationtop);
                    mGirdViewtop.setVisibility(View.VISIBLE);
                    break;
            }
        }
    };

    //注册广播
    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionCloseAlbum);
        myIntentFilter.addAction(ACTIONs.actionUpdateUpNum);
        myIntentFilter.addAction("updatetopgridview");
        myIntentFilter.addAction("topgridviewopen");
        myIntentFilter.addAction("topgridviewclose");
        this.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected void onDestroy() {
//        if (mainImage) {
//            SelectedImg.mSelectedImage.clear();
//            AiteSelectActivity.phoneNames.clear();
//            MicAddActivity.mMp3FileName = "";
//            MainActivity.mp3IsExist = false;
//            MainActivity.micUrl = "";
//            MainActivity.micpath = "";
//            MainActivity.locationTx = "";
//        }
        SelectedImg.mSelectedImage.clear();
        SelectedImg.mSelectedVideo.clear();
        this.unregisterReceiver(mBroadcastReceiver);
        if (mProgressDialog != null)
            mProgressDialog.dismiss();
        super.onDestroy();
    }


    public void onResume() {
        super.onResume();
//        topAdapter.notifyDataSetChanged();
//        sendBroadcast(new Intent("updatebuttomgridview"));
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
